/* ////////////////  KV measurement  ////////////////

This script experimentally measures the KV value of a brushless motor. 
Make sure you have the correct number of poles in the setup tab. 
DO NOT USE WITH A PROPELLER. The motor will spin at full speed.

You must select the Electrical RPM Sensor as "Main Sensor" in the Setup tab. 

///////////////// Beginning of the script //////////////// */

rcb.console.print("Initializing ESC...");
rcb.output.set("esc",1000);
rcb.wait(rampESC, 4);

function rampESC(){
    //For safety reasons, the esc is slowly ramped to 100%
    rcb.output.ramp("esc", 1000, 2000, 15, recordData); 
}

function recordData(){
    rcb.console.print("Waiting to reach steady speed");
    rcb.wait(function(){ // Wait for motor speed to stabilize
        rcb.sensors.read(calculateKV, 100);
    }, 4);
}

function calculateKV(result) {
    var kV = result.motorElectricalSpeed.workingValue/result.voltage.workingValue;
    rcb.console.print("Motor KV value: " + Math.round(kV));  
    rcb.endScript();
}